import json
from typing import Any, List

from application.db.elastic_db.base_elastic import BaseElasticSearch
from application.etl.write.base_batch_observer import BaseBatchObserver


class NsfcToEsWrite(BaseBatchObserver, BaseElasticSearch):
    index_name = "test_information_index"

    def process_batch(self, batch_data):
        success_count = 0
        fail_count = 0

        for doc in batch_data:
            try:
                # 将对象转换为字典
                doc['info_type'] = doc['info_type'].as_dict()
                doc['source_info'] = doc['source_info'].as_dict()
                doc['area_info'] = doc['area_info'].as_dict()
                doc['apply_info'] = doc['apply_info'].as_dict()
                doc['sections'] = [item.as_dict() for item in doc['sections']]
            except Exception as e:
                self.logger.error("文档转换失败，ID：%s，错误信息：%s", doc.get("information_id"), str(e))
                fail_count += 1
                continue

            # 单条写入Elasticsearch
            try:
                result = self.index_by_elastic(doc, doc["information_id"])
                if result.get("result"):
                    success_count += 1
                else:
                    fail_count += 1
                    self.logger.error("单条插入失败，文档ID：%s，错误信息：%s", doc["information_id"], result.get("msg"))
            except Exception as e:
                fail_count += 1
                self.logger.error("单条插入异常，文档ID：%s，错误信息：%s", doc["information_id"], str(e))

        self.logger.info("单条插入完成，成功：%d 条，失败：%d 条。", success_count, fail_count)
